﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Windvoice.Authorize;
using System.Configuration;
using System.Text;

namespace Windvoice.Controllers
{
    public class UserController : Windvoice.Framework.ControllerBase
    {
        //
        // GET: /User/
        public ActionResult Connect()
        {
            var ReturnUrl = Request.QueryString["returnurl"];

            if (System.Web.HttpContext.Current.Session["oauth_provider"] == null || System.Web.HttpContext.Current.Session["oauth_connector"] == null)
                throw new Exception("无法识别OAuth供应商");

            OAuthProvider oAuthProvider = (OAuthProvider)System.Web.HttpContext.Current.Session["oauth_provider"];
            IOAuthConnector connector = (IOAuthConnector)System.Web.HttpContext.Current.Session["oauth_connector"];

            //if(p==null)
            //    return View("_404");

            connector.GetAccessToken();
            User u = connector.GetUser();

            u.SaveFromConnector();
            System.Web.HttpContext.Current.Session["user"] = u;

            return Redirect(ReturnUrl);
        }

        [HttpPost]
        public ActionResult Connect(int? id)
        {
            var CallbackUrl = ConfigurationManager.AppSettings["weiboCallbackUrl"];
            var ReturnUrl = Request.QueryString["returnurl"];

            var Provider = Request.Form["provider"];

            object p = Enum.Parse(typeof(OAuthProvider), Provider);
            //if(p==null)
            //    return View("_404");

            OAuthProvider oAuthProvider = (OAuthProvider)p;
            IOAuthConnector connector = OAuthFactory.CreateConnector(oAuthProvider);

            System.Web.HttpContext.Current.Session["oauth_provider"] = oAuthProvider;
            System.Web.HttpContext.Current.Session["oauth_connector"] = connector;

            var Url = connector.GetRequestToken(String.Format("{0}?returnurl={1}", CallbackUrl, Server.UrlEncode(ReturnUrl)));

            StringBuilder UrlStringBuilder = new StringBuilder(Url);
            UrlStringBuilder.Append("&oauth_callback=").Append(CallbackUrl).Append("?returnurl=").Append(Server.UrlEncode(ReturnUrl));

            return Redirect(UrlStringBuilder.ToString());
        }
    }
}
